package com.h3bpm.web.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.cloudpivot.ResponseResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.Sessions;
import com.h3bpm.web.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@RequestMapping("/Portal/MessageCenterController")
@Controller
public class MessageCenterController extends ControllerBase {

    private static final Logger logger = LoggerFactory.getLogger(MessageCenterController.class);

    /**
     * 流程访问的服务器地址
     * "http://10.50.132.106/";
     */
    @Value("${push-url.h3bpmPcUrl}")
    private String h3bpmPcUrl;

    /***
     * 中车推送中心地址
     *  private static String pushUrl = "http://10.48.200.12:8081/pushsys/platform/platFormJsonPushMsg.act";
     */
    @Value("${push-url.appPushUrl}")
    private  String pushUrl;

    /**
     * 中车通推送地址
     * "http://im.crrcgc.cc:7772/pbs/IM/pushNotifyNotAuth"
     */
    @Value("${push-url.appPushUrl2}")
    private  String zhongCheTongPushUrl2;

    /**
     * 样例数据
     * <p>
     * <p>
     * {
     * "appName": "com.crrcqsy.portal",
     * "custom": {
     * "type": "1",
     * "insideAppName": "动态传值"
     * },
     * "param": "",
     * "userAccountList": "xxxxxxxxx（OA账号，例如:010099900302,010099900194）",
     * "sender": "",
     * "title": "动态传值（例如：OA待办）",
     * "content": "动态传值（例如：你有一条OA待办消息）"
     * }
     * <p>
     * //创建时间的时间戳
     * map.put("createTime",createTime);
     * //发起人
     * map.put("promoter",promoter);
     * //发起部门
     * map.put("promoterOrg",promoterOrg);
     * //当前节点名称
     * map.put("node",node);
     * //接收人user
     * map.put("userAccountList",receiverUserCode);
     * // 消息标题
     * map.put("title",title);
     * // 消息内容
     * map.put("content",name);
     * // sequenceNo
     * map.put("sequenceNo",sequenceNo);
     * // 创建时间点
     * map.put("initiationTime",initiationTime);
     * // pc端的流程地址，不含ip和端口号
     * map.put("pcUrl",pcUrl);
     */
    @RequestMapping("addMsg")
    @ResponseBody
    public ResponseResult addMsg(@RequestBody JSONObject jsonObjectString) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        JSONObject map = new JSONObject();
        logger.info("取到h3bpm信息中心的参数了, h3bpm信息中心的参数结果是 {}", jsonObjectString);
        Object pcUrl = jsonObjectString.get("pcUrl");
        Object promoter = jsonObjectString.get("promoter");
        Object userAccountList = jsonObjectString.get("userAccountList");
        Object title = jsonObjectString.get("title");
        Object content = jsonObjectString.get("content");
        HashMap<String, Object> urlMap = new HashMap<>(1);
        urlMap.put("appUrl", "/" + pcUrl + "&IsMobile=true");
        HashMap<String, Object> innerMap = new HashMap<>(2);
        innerMap.put("type", 2);
        innerMap.put("insideAppName", "bpm");
        map.put("custom", innerMap);
        map.put("param", urlMap);
        map.put("appName", "com.crrcqsy.portal");
        map.put("sender", promoter);
        map.put("userAccountList", userAccountList);
        map.put("title", title);
        map.put("content", content);
        logger.info("开始推送给消息中心, 给推送中心的参数是 {}", map);
        logger.info("开始推送给消息中心, 推送中心地址是 {}", pushUrl);

        try {
            String returnStr = HttpClientUtils.httpPost(pushUrl, map.toJSONString());
            logger.info("获得消息中心返回值, 返回值为 {}", returnStr);
            if (returnStr != null && JSON.parseObject(returnStr) != null && JSON.parseObject(returnStr).getInteger("status") == 1) {
                rst.setErrmsg("成功");
                rst.setErrcode(0L);
                logger.info("推送消息中心成功了");
                return rst;
            }
            logger.info("推送消息中心失败了");
            rst.setErrmsg("失败");
            return rst;
        } catch (Exception e) {
            logger.warn("推送消息中心失败了, 失败原因是 message ={}", e.getMessage());
        }
        rst.setErrmsg("失败");
        return rst;
    }

    /**
     *中车通样例数据
     * systemId:系统id,必填，用来标识每个系统
     * appMap.put("systemId",systemId) ;
     * appCode:应用编码,必填，区分会话
     * appMap.put("appCode","");
     * title:标题 （长度16），必填
     * appMap.put("title","你有一条新流程");
     * subTitle：副标题，必填，沟通页面上cell界面显示（长度16）
     * appMap.put("subTitle","bpm系统");
     * contTitle：内容标题，必填，在列表页面的cell上显示（长度12）
     * appMap.put("contTitle","bpm系统");
     * summary：概述，必填，进入列表页面后cell界面显示
     * appMap.put("summary",innerMap);
     * recvtype：标识接收者字段使用哪个字段，必填，（登录账号，员工号等等） 缺少或值为0时 登录账号；2，员工号
     * appMap.put("recvtype","2");
     * receiver：接收者账号多个（单人），必填
     * appMap.put("receiver",userAccountList);
     *
     * property：summary嵌入字段。必填，内容属性；这里用作通知标题
     * innerMap.put("property",title);
     * text：summary嵌入字段。必填，内容正文；这里用作消息正文
     * innerMap.put("text",content);
     */
    @RequestMapping("appAddMsg")
    @ResponseBody
    public ResponseResult addMsg1(@RequestBody JSONObject jsonObjectString) {
        String urlAddr ="/Portal/MessageCenterController/ssoApi";
        logger.info("appPushUrl :  "+zhongCheTongPushUrl2);
        logger.info("pushUrl : " + pushUrl);
        logger.info("h3bpmPcUrl : "+h3bpmPcUrl);
        ResponseResult rst = new ResponseResult(-1L, "", null);
        logger.info("取到h3bpm信息中心的参数, h3bpm信息中心的参数结果是 {}", jsonObjectString);
        Object pcUrl = jsonObjectString.get("pcUrl");
        Object promoter = jsonObjectString.get("promoter");
        Object userAccountList = jsonObjectString.get("userAccountList");
        Object title = jsonObjectString.get("title");
        Object content = jsonObjectString.get("content");
//        HashMap<String, Object> urlMap = new HashMap<>(1);
//        urlMap.put("appUrl", "/" + pcUrl + "&IsMobile=true");
        List<Object> userList = new ArrayList<>();
        userList.add(userAccountList);
        List<Object> objList = new ArrayList<>();
        HashMap<String, Object> innerMap = new HashMap<>(2);
        innerMap.put("property",title);
        innerMap.put("text",content);
        objList.add(innerMap);
        logger.info("json : {}",objList.toString());
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer append = stringBuffer.append("[{\"property\":\"").append(title).append("\",\"text\":\"").append(content).append("\"}]");
        String url =h3bpmPcUrl+urlAddr+"?userId="+userAccountList+"&urlAddr="+h3bpmPcUrl+ "/" + pcUrl;

        JSONObject appMap = new JSONObject();
        appMap.put("url",url);
        appMap.put("systemId","da8d83c3733711e7b684204747749430");
        appMap.put("appCode","010400017798");
        appMap.put("title","业务系统通知");
        appMap.put("subTitle","业务表单化系统");
        appMap.put("contTitle","业务表单化系统");
//        appMap.put("summary", objList.toString());
        appMap.put("summary",append);
        appMap.put("recvtype","2");
        appMap.put("receiver",userList);
        logger.info("开始推送给消息中心, 给推送中心的参数是 {}", appMap);
        logger.info("开始推送给消息中心, 推送中心地址是 {}", zhongCheTongPushUrl2);
        try {
            String returnStr = HttpClientUtils.doPost(zhongCheTongPushUrl2, appMap.toJSONString());
            logger.info("获得中车通消息中心返回值, 返回值为 {}", returnStr);
            if (returnStr != null && JSON.parseObject(returnStr) != null && "success".equals(JSON.parseObject(returnStr).getString("statusMsg")) ) {
                rst.setErrmsg("成功");
                rst.setErrcode(0L);
                logger.info("推送消息中心成功了");
                return rst;
            }
            logger.info("推送消息中心失败了");
            rst.setErrmsg("失败");
            return rst;
        } catch (Exception e) {
            logger.warn("推送消息中心失败了, 失败原因是 message ={}", e.getMessage());
        }
        rst.setErrmsg("失败");
        return rst;
    }
    @RequestMapping("updateMsg")
    @ResponseBody
    public ResponseResult updateMsg(@RequestBody JSONObject jsonObjectString) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        rst.setErrmsg("成功");
        rst.setErrcode(0L);
        logger.info("取到h3bpm信息中心的参数了, h3bpm信息中心的参数结果是 {}", jsonObjectString);
        return rst;
    }

    @RequestMapping("ssoApi")
    @ResponseBody
    public ResponseResult ssoApi(HttpServletRequest request, HttpServletResponse response) {
        Enumeration<?> enu=request.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            System.out.println(paraName+": "+request.getParameter(paraName));
        }
        String urlAddr=request.getParameter("urlAddr");
//        String userName=request.getParameter("userName");
        String userId=request.getParameter("userId");
        logger.info("urlAddr : {}",urlAddr);
        ResponseResult rst = new ResponseResult(-1L, "", null);
        if ("".equals(userId) || null == userId) {
            rst.setErrmsg("用户为空");
            return rst;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("userId ={}", userId);
        }
        UserValidator userValidator = super.getUserValidator();
        String userCode;
        User user = null;
        try {
            // 检查是否已登陆
            if (userValidator != null && (user = userValidator.getUser()) != null) {
                userCode = user.getCode();
                logger.info("userCode ={}", userCode);
            }
            user = getEngine().getOrganization().GetUserByCode(userId);
            if (user!=null){
                ssoSession(request, user);
                logger.info("userCode ={}", user.getCode());
                response.sendRedirect(urlAddr);
            }else {
                rst.setErrmsg("此用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rst;
    }

    private void ssoSession(HttpServletRequest request, User user) throws Exception {
        UserValidator userValidator = new UserValidator(getEngine(), user.getObjectId(), null, null);

        request.getSession().setAttribute(Sessions.GetUserValidator(), userValidator);
    }
    @Override
    public String getFunctionCode() {
        return null;
    }
}
